package com.yangzb.http.apache;


import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings({ "resource", "deprecation" })
@Slf4j
public class HttpClientUtil {

    private HttpClientUtil(){}


    /**
     * 发送HTTP_GET请求
     * @param reqUrl    请求地址(含参数)
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @return 远程主机响应正文
     */
    public static String sendGetRequest(String reqUrl, String decodeCharset){
        long responseLength = 0;       //响应长度
        String responseContent = null; //响应内容
        HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
        HttpGet httpGet = new HttpGet(reqUrl);           //创建org.apache.http.client.methods.HttpGet
        try{

            HttpResponse response = httpClient.execute(httpGet); //执行GET请求
            HttpEntity entity = response.getEntity();            //获取响应实体
            if(null != entity){
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity); //Consume response content
            }
            System.out.println("请求地址: " + httpGet.getURI());
            System.out.println("响应状态: " + response.getStatusLine());
            System.out.println("响应长度: " + responseLength);
            System.out.println("响应内容: " + responseContent);
        }catch(ClientProtocolException e){
            log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
        }catch(ParseException e){
            log.error(e.getMessage(), e);
        }catch(IOException e){
            log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
        }
        return responseContent;
    }


    /**
     * 发送HTTP_POST请求
     * @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要
     */
    public static String sendPostRequest(String reqUrl, String sendData, boolean isEncoder){
        return sendPostRequest(reqUrl, sendData, isEncoder, null, null,null);
    }


    /**
     * 发送HTTP_POST请求
     * @param reqUrl        请求地址
     * @param params      请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
     * @return 远程主机响应正文
     */
    public static String sendPostRequest(String reqUrl, Map<String, String> params, Integer... connectTimeout){
        return sendPostRequest(reqUrl,params,null,null,null,connectTimeout);
    }
    /**
     * 发送HTTP_POST请求
     * @param reqUrl        请求地址
     * @param params      请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
     * @return 远程主机响应正文
     */
    public static String sendPostRequest(String reqUrl, Map<String, String> params,String contentType){
        return sendPostRequest(reqUrl,params,null,null,contentType,null);
    }
    /**
     * 发送HTTP_POST请求
     * @param reqUrl        请求地址
     * @param sendData      请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
     * @param isEncoder     请求数据是否需要encodeCharset编码,true为需要
     * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @return 远程主机响应正文
     */
    public static String sendPostRequest(String reqUrl, String sendData,boolean isEncoder, String encodeCharset, String decodeCharset,String contentType){
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(reqUrl);

        //httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
        if(StrUtil.isBlank(contentType)){
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        }else{
            httpPost.setHeader(HTTP.CONTENT_TYPE, contentType);
        }

        try{
            if(isEncoder){
                StringEntity se = new StringEntity(sendData,encodeCharset==null ? "UTF-8" : encodeCharset);
                httpPost.setEntity(se);
            }else{
                httpPost.setEntity(new StringEntity(sendData));
            }

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        }catch(Exception e){
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }
    /**
     * 发送HTTP_POST请求
     * @param reqUrl        请求地址
     * @param sendData      请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
     * @param isEncoder     请求数据是否需要encodeCharset编码,true为需要
     * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @param connectTimeout 超时时间
     * @return 远程主机响应正文
     */
    public static String sendPostRequest(String reqUrl, String sendData,boolean isEncoder, String encodeCharset, String decodeCharset,String contentType,Integer... connectTimeout){
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(reqUrl);

        //httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
        if(StrUtil.isBlank(contentType)){
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        }else{
            httpPost.setHeader(HTTP.CONTENT_TYPE, contentType);
        }

        try{
            if(isEncoder){
                StringEntity se = new StringEntity(sendData,encodeCharset==null ? "UTF-8" : encodeCharset);
                httpPost.setEntity(se);
            }else{
                httpPost.setEntity(new StringEntity(sendData));
            }

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        }catch(Exception e){
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    public static String sendPostRequest(String reqUrl, String param, String encodeCharset, String decodeCharset, String contentType,Integer... connectTimeout) throws IOException {
        String responseContent = null;
        HttpClient httpClient =new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(reqUrl);

        try {
            StringEntity myEntity = new StringEntity(param, encodeCharset);
            if (StrUtil.isBlank(contentType)) {
                myEntity.setContentType("application/x-www-form-urlencoded");
            } else {
                myEntity.setContentType(contentType);
            }

            if (connectTimeout != null && connectTimeout.length > 0) {
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout[0])
                        .setSocketTimeout(connectTimeout[0]).build();
                httpPost.setConfig(requestConfig);
            }

            httpPost.setEntity(myEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        } catch (Exception var14) {
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息如下", var14);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }

    /**
     * 发送HTTP_POST请求
     * @param reqUrl        请求地址
     * @param params        请求参数
     * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @return 远程主机响应正文
     */
    public static String sendPostRequest(String reqUrl, Map<String, String> params, String encodeCharset, String decodeCharset,String contentType, Integer... connectTimeout){
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();;
        HttpPost httpPost = new HttpPost(reqUrl);
        List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
        if(params!=null){
            for(Map.Entry<String,String> entry : params.entrySet()){
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        try{
            UrlEncodedFormEntity urlEntity=new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset);
            if(StrUtil.isNotBlank(contentType)){
                httpPost.setHeader(HTTP.CONTENT_TYPE, contentType);
                urlEntity.setContentType(contentType);
            }
            httpPost.setEntity(urlEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        }catch(Exception e){
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }

    /**
     * 只有一个参数并无名称
     * @Title: sendPostRequest
     * @param reqUrl
     * @param param
     * @param encodeCharset
     * @param decodeCharset
     * @return
     * @return String
     */
    public static String sendPostRequest(String reqUrl, String param, String encodeCharset, String decodeCharset,String contentType){
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(reqUrl);

        try{
            StringEntity myEntity = new StringEntity(param, encodeCharset);
            if(StrUtil.isBlank(contentType)){
                myEntity.setContentType("application/x-www-form-urlencoded");
            }else{
                myEntity.setContentType(contentType);
            }
            httpPost.setEntity(myEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        }catch(Exception e){
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }

    public static String sendPostRequest(String reqUrl, String param, String encodeCharset, String decodeCharset,
                                         String contentType, Map<String,String> headers, Integer... connectTimeout) throws IOException {
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(reqUrl);

        try {
            StringEntity myEntity = new StringEntity(param, encodeCharset);
            if (StrUtil.isBlank(contentType)) {
                myEntity.setContentType("application/x-www-form-urlencoded");
            } else {
                myEntity.setContentType(contentType);
            }
            if (headers!=null && headers.size()>0){
                for(Map.Entry<String, String> entry : headers.entrySet()){
                    httpPost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            if (connectTimeout != null && connectTimeout.length > 0) {
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout[0])
                        .setSocketTimeout(connectTimeout[0]).build();
                httpPost.setConfig(requestConfig);
            }

            httpPost.setEntity(myEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        } catch (Exception var14) {
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息如下", var14);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    /**
     * 发送HTTPS_POST请求
     * @param reqUrl 请求地址
     * @param params 请求参数
     * @return
     */
    public static String sendPostSSLRequest(String reqUrl, Map<String, String> params){
        return sendPostSSLRequest(reqUrl, params, null, null);
    }



    /**
     * 发送HTTPS_POST请求
     * @param reqUrl        请求地址
     * @param params        请求参数
     * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @return 远程主机响应正文
     */
    public static String sendPostSSLRequest(String reqUrl, Map<String, String> params, String encodeCharset, String decodeCharset){
        String responseContent = "";
        HttpClient httpClient =  new DefaultHttpClient();
        X509TrustManager xtm = new X509TrustManager(){
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            @Override
            public X509Certificate[] getAcceptedIssuers() {return null;}
        };
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

            HttpPost httpPost = new HttpPost(reqUrl);

            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            for(Map.Entry<String,String> entry : params.entrySet()){
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            log.error("与[" + reqUrl + "]通信过程中发生异常,堆栈信息为", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }


    /**
     * 发送HTTP_POST请求
     * @param reqUrl   请求地址
     * @param sendData 发送到远程主机的正文数据
     * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
     */
    public static String sendPostRequestByJava2(String reqUrl, String sendData,String cmdCode){
        HttpURLConnection urlConnection = null;
        OutputStream out = null; //写
        BufferedReader reader = null;   //读
        int httpStatusCode = 0;  //远程主机响应的HTTP状态码
        try{
            URL sendUrl = new URL(reqUrl);
            urlConnection = (HttpURLConnection)sendUrl.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);        //指示应用程序要将数据写入URL连接,其值默认为false
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("content-type",
                    "application/x-java-serialized-object");
            urlConnection.setRequestProperty("CMD_CODE",cmdCode);
            urlConnection.setConnectTimeout(10000); //30秒连接超时
            urlConnection.setReadTimeout(10000);    //30秒读取超时

            out = urlConnection.getOutputStream();
            out.write(sendData.toString().getBytes());

            //清空缓冲区,发送数据
            out.flush();

            //获取HTTP状态码
            httpStatusCode = urlConnection.getResponseCode();


            //该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
            //若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
            //respData = httpURLConnection.getResponseMessage();

//			//处理返回结果
//			BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
//			String row = null;
//			String respData = "";
//			if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
//				respData = row;              //HTTP协议POST方式的最后一行数据为正文数据
//			}
//			br.close();
//			if(httpStatusCode!=200){
//				throw new ApplicationException("接口调用出错");
//			}
//			new InputStreamReader(in, cs).r
            if(httpStatusCode==200){
                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
            }else{
                reader = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream(),"UTF-8"));
            }
            String line = null;
            StringBuilder buffer = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        }catch(Exception e){
            log.error("",e);
            log.error("接口调用出错",e);
            throw new RuntimeException("接口调用出错："+e.getMessage());
        }finally{
            if(out != null){
                try{
                    out.close();
                }catch (Exception e){
                    log.error("关闭输出流时发生异常,堆栈信息如下", e);
                }
            }
            if(reader != null){
                try{
                    reader.close();
                }catch(Exception e){
                    log.error("关闭输入流时发生异常,堆栈信息如下", e);
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
                urlConnection = null;
            }
        }
    }


    /**
     * 发送HTTP_POST请求
     * @param reqUrl   请求地址
     * @param sendData 发送到远程主机的正文数据
     * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
     */
    public static String sendPostRequestByJava(String reqUrl, String sendData){
        HttpURLConnection urlConnection = null;
        OutputStream out = null; //写
        BufferedReader reader = null;   //读
        int httpStatusCode = 0;  //远程主机响应的HTTP状态码
        try{
            URL sendUrl = new URL(reqUrl);
            urlConnection = (HttpURLConnection)sendUrl.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);        //指示应用程序要将数据写入URL连接,其值默认为false
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type",
                    "application/json");
            urlConnection.setConnectTimeout(10000); //30秒连接超时
            urlConnection.setReadTimeout(10000);    //30秒读取超时

            out = urlConnection.getOutputStream();
            out.write(sendData.toString().getBytes());

            //清空缓冲区,发送数据
            out.flush();

            //获取HTTP状态码
            httpStatusCode = urlConnection.getResponseCode();


            //该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
            //若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
            //respData = httpURLConnection.getResponseMessage();

//			//处理返回结果
//			BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
//			String row = null;
//			String respData = "";
//			if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
//				respData = row;              //HTTP协议POST方式的最后一行数据为正文数据
//			}
//			br.close();
//			if(httpStatusCode!=200){
//				throw new ApplicationException("接口调用出错");
//			}
//			new InputStreamReader(in, cs).r
            if(httpStatusCode==200){
                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
            }else{
                reader = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream(),"UTF-8"));
            }
            String line = null;
            StringBuilder buffer = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        }catch(Exception e){
            log.error("",e);
            log.error("接口调用出错",e);
            throw new RuntimeException("接口调用出错："+e.getMessage());
        }finally{
            if(out != null){
                try{
                    out.close();
                }catch (Exception e){
                    log.error("关闭输出流时发生异常,堆栈信息如下", e);
                }
            }
            if(reader != null){
                try{
                    reader.close();
                }catch(Exception e){
                    log.error("关闭输入流时发生异常,堆栈信息如下", e);
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
                urlConnection = null;
            }
        }
    }

    /**
     * 发送HTTP_POST请求
     * @param reqUrl   请求地址
     * @param sendData 发送到远程主机的正文数据
     * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
     */
    public static String sendPostRequestByJavaSoap(String reqUrl, String sendData){
        HttpURLConnection urlConnection = null;
        OutputStream out = null; //写
        BufferedReader reader = null;   //读
        int httpStatusCode = 0;  //远程主机响应的HTTP状态码
        try{
            URL sendUrl = new URL(reqUrl);
            urlConnection = (HttpURLConnection)sendUrl.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);        //指示应用程序要将数据写入URL连接,其值默认为false
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("content-type",
                    "application/x-java-serialized-object");
            urlConnection.setRequestProperty("CMD_CODE","INTF_QRY_REPORT_DATA_NEW");
            urlConnection.setConnectTimeout(10000); //30秒连接超时
            urlConnection.setReadTimeout(10000);    //30秒读取超时

            out = urlConnection.getOutputStream();
            out.write(sendData.toString().getBytes());

            //清空缓冲区,发送数据
            out.flush();

            //获取HTTP状态码
            httpStatusCode = urlConnection.getResponseCode();

            if(httpStatusCode==200){
                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"GBK"));
            }else{
                reader = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream(),"GBK"));
            }
            String line = null;
            StringBuilder buffer = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return (buffer.toString().replaceAll("&lt;", "<")).replaceAll("&gt;", ">");
        }catch(Exception e){
            log.error("",e);
            log.error("接口调用出错",e);
            throw new RuntimeException("接口调用出错："+e.getMessage());
        }finally{
            if(out != null){
                try{
                    out.close();
                }catch (Exception e){
                    log.error("关闭输出流时发生异常,堆栈信息如下", e);
                }
            }
            if(reader != null){
                try{
                    reader.close();
                }catch(Exception e){
                    log.error("关闭输入流时发生异常,堆栈信息如下", e);
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
                urlConnection = null;
            }
        }
    }
}

